package com.edu.security;


import com.edu.entity.Permission;
import com.edu.entity.Role;
import com.edu.entity.User;
import com.edu.service.PermissionService;
import com.edu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据传入的用户名，去数据库中获取信息
        User dbUser = userService.getUserByName(username);
        //2.判断是否为空
        if (dbUser!=null){
            //3.用户的信息中会包含角色清单
            Set<Role> roles = dbUser.getRoles();
            Set<GrantedAuthority> authorities = new HashSet();
            //4.把每个角色‘标识符’加入到权限列表中
            roles.forEach(
                    (R)->{
                        String ROLE = "ROLE_" + R.getRoleName();
                        authorities.add( new SimpleGrantedAuthority(ROLE));
                    }
            );
            //5.获取用户的权限信息，加入到权限列表中
            Integer roleId = null;
            Set<Permission> perms = new HashSet();
            if( roles!=null){
                Role role = roles.iterator().next();
                roleId = role.getId();
                perms = permissionService.getPermissionByRoleId(roleId);
            }
            perms.forEach((P)->{
                authorities.add( new SimpleGrantedAuthority(P.getPermName()));
            });
            //6.创建UserSecurity对象并返回
            return new UserSecurity(dbUser,authorities);
        }
        return null;
    }
}
